package edu.upc.autopartescybershop.web;

import edu.upc.autopartescybershop.domain.Categoria;
import edu.upc.autopartescybershop.service.CategoriaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author Carlos
 */
@Controller
public class CategoriasController
{

    @Autowired
    CategoriaService categoriaService;

    @RequestMapping(value = "/categorias.htm", method = RequestMethod.GET)
    public ModelAndView listadoCategorias()
    {
        ModelAndView mav = new ModelAndView("categorias");
        mav.addObject("listadoCategorias", categoriaService.obtenerCategorias());
        return mav;
    }

    @RequestMapping(value = "/categorias_form.htm", method = RequestMethod.GET)
    public
    @ModelAttribute("categoria")
    Categoria setupForm(@RequestParam("accion") String accion, @RequestParam("id") int codigoCategoria)
    {
        if (accion.equals("E"))
        {
            return categoriaService.obtenerCategoria(codigoCategoria);
        }
        else if(accion.equals("D"))
        {
            Categoria categoria=categoriaService.obtenerCategoria(codigoCategoria);
            categoria.setNombre("-*D*-");
            return categoria;
        }
        else if (accion.equals("N"))
        {
            return new Categoria();
        }
        else
        {
            return null;
        }
    }

    @RequestMapping(value = "/categorias_form.htm", method = RequestMethod.POST)
    public String onsubmit(@ModelAttribute("categoria") Categoria categoria,
            BindingResult result, SessionStatus status, @RequestParam("accion") String accion, @RequestParam("id") int codigoCategoria)
    {
        if (accion.equals("E") || accion.equals("N"))
        {
            categoriaService.grabarCategoria(categoria);
        }
        else if (accion.equals("D"))
        {
            categoriaService.eliminarCategoria(codigoCategoria);
        }
        return "redirect:/categorias.htm";
    }
}
